package com.ailanyin.modules.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ailanyin.common.log.model.BaseUseLog;
import com.ailanyin.common.log.service.BaseLogService;
import com.ailanyin.common.security.constants.SecurityConstant;
import com.ailanyin.common.security.utils.TokenUtil;
import com.ailanyin.modules.system.domain.SysUseLog;
import com.ailanyin.modules.system.mapper.SysUseLogMapper;
import com.ailanyin.modules.system.service.ISysUseLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 操作日志
 *
 * @author ailanyin
 */
@Service
public class SysUseLogServiceImpl implements ISysUseLogService, BaseLogService {
    @Resource
    private SysUseLogMapper useLogMapper;

    /**
     * 新增操作日志
     *
     * @param operLog 操作日志对象
     */
    @Override
    public void insertUseLog(SysUseLog operLog) {
        useLogMapper.insertUseLog(operLog);
    }

    /**
     * 查询系统操作日志集合
     *
     * @param operLog 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public List<SysUseLog> selectUseLogList(SysUseLog operLog) {
        return useLogMapper.selectUseLogList(operLog);
    }

    /**
     * 批量删除系统操作日志
     *
     * @param ids 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int deleteUseLogByIds(List<Long> ids) {
        return useLogMapper.deleteUseLogByIds(ids);
    }

    /**
     * 查询操作日志详细
     *
     * @param operId 操作ID
     * @return 操作日志对象
     */
    @Override
    public SysUseLog selectUseLogById(Long operId) {
        return useLogMapper.selectUseLogById(operId);
    }

    /**
     * 清空操作日志
     */
    @Override
    public void cleanUseLog() {
        useLogMapper.cleanUseLog();
    }

    @Override
    public void saveSysLog(BaseUseLog useLog, String token) {

        // 请勿使用 SecurityUtil.getLoginUsername, ThreadLocal在子线程无法传递
        if (StrUtil.isNotBlank(token)) {
            String authToken = token.substring(SecurityConstant.TOKEN_HEAD.length());
            String username = TokenUtil.getUserNameFromToken(authToken);
            useLog.setOperatorName(username);
        }

        useLogMapper.saveSysLog(useLog);
    }
}
